﻿package com.netafull;

import java.util.List;

import org.apache.commons.lang3.StringEscapeUtils;

import com.netafull.analyze.AnalyzeXMLForContent;
import com.netafull.analyze.AnalyzeXMLForUrl;
import com.netafull.analyze.Content;
import com.netafull.analyze.ShortUrl;
import com.netafull.twitter.TwitterPage;
import com.netafull.util.CloseUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

public class NewsContent extends ShowAdActivity implements OnClickListener{
	
	public static final int STATUS_OK = 1;
	public static final int STATUS_ERR = 0;
	
	public static int i = 0;
	
	WebView webView;
	String newsUrl;
	TextView tv_title;
	ImageButton iv_back;
	ImageButton iv_comment;
	
	AnalyzeXMLForContent analyzeXML;
	AnalyzeXMLForContent analyzeXML1;
	Content content;
	String sDecode;
	
	String newsTitle;
	int newsID;
	
	Handler handler;
	View progress;
	
	boolean menu_display = false;
	PopupWindow menuWindow;
	View layout;
	LayoutInflater inflater;
	
	Button btn01;//读者评论
	Button btn02;//发邮件
	Button btn03;//twitter
	Button btn04;//取消
	
	String contentShotUrl;
	
	boolean flag = false;
	
	Thread t;
	
	AnalyzeXMLForUrl analyze;
	List<ShortUrl> list;
	
	boolean b = false;
	
	SharedPreferences sp;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newscontent);
		
		show();
		
		sp = getSharedPreferences("netafull",Context.MODE_PRIVATE);
		
		CloseUtil.activityList.add(NewsContent.this);
		
		analyze = new AnalyzeXMLForUrl();
		
		analyzeXML = new AnalyzeXMLForContent();
		analyzeXML1 = new AnalyzeXMLForContent();
		
		tv_title = (TextView) findViewById(R.id.newscontent_title);
		iv_back = (ImageButton) findViewById(R.id.newscontent_button_left);
		iv_comment = (ImageButton) findViewById(R.id.newscontent_button_right);
		iv_comment.setEnabled(false);
		
		
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		newsTitle = bundle.getString("title");
		newsID = bundle.getInt("id");
		//tv_title.setText(newsTitle);
		tv_title.setText(getResources().getString(R.string.app_name));
		
		progress = findViewById(R.id.list_progress);
		
		inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
        layout = inflater.inflate(R.layout.popupwindow, null);
        
        btn01 = (Button) layout.findViewById(R.id.btn_popup01);
		btn02 = (Button) layout.findViewById(R.id.btn_popup02);
		btn03 = (Button) layout.findViewById(R.id.btn_popup03);
		btn04 = (Button) layout.findViewById(R.id.btn_popup04);
		//btn01.setOnClickListener(this);btn01.getPaint().setFakeBoldText(true);
		//btn02.setOnClickListener(this);btn02.getPaint().setFakeBoldText(true);
		//btn03.setOnClickListener(this);btn03.getPaint().setFakeBoldText(true);
		//btn04.setOnClickListener(this);btn04.getPaint().setFakeBoldText(true);
		btn01.setOnClickListener(this);
		btn02.setOnClickListener(this);
		btn03.setOnClickListener(this);
		btn04.setOnClickListener(this);
        //弹出menu 初始化
        menuWindow = new PopupWindow(layout,LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		
		newsUrl = getResources().getString(R.string.getreport_url) + newsID+"&device=Android";
		webView = (WebView) findViewById(R.id.webview);
		WebSettings webSetting = webView.getSettings();
		webSetting.setJavaScriptEnabled(true);
		
		// 在自己的WebView中打开链接
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				// TODO Auto-generated method stub
				super.onPageStarted(view, url, favicon);
			}
			@Override
			public void onPageFinished(WebView view, String url) {
				// TODO Auto-generated method stub
				super.onPageFinished(view, url);
				flag = true;
				if(iv_comment!=null){
					iv_comment.setEnabled(true);
				}
			}
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				// TODO Auto-generated method stub
				b = true;
				Intent intent = new Intent(NewsContent.this, NewNews.class);
				System.out.println(url);
				Bundle bundle = new Bundle();
				bundle.putString("url", url);
				intent.putExtras(bundle);
				NewsContent.this.startActivityForResult(intent,100);
				return true;
			}
		});
		
		iv_back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (t.isAlive()) {
					t.interrupt();
					System.out.println("线程正在运行，强行中断");
				}
				NewsContent.this.finish();
			}
		});
		iv_comment.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				openMenu();
				System.out.println("***********");
			}
		});
		handler = new Handler(){
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case STATUS_OK://数据请求成功
					progress.setVisibility(View.GONE);
					break;
				case STATUS_ERR://数据请求失败
					//showNetBusy();//显示请求超时提示框
					break;
				}
			};
		};
		t = new Thread(){
			public void run() {
				Message message = new Message();
				analyzeXML = new AnalyzeXMLForContent();
				try {
					content = analyzeXML.getRss(newsUrl);
					
					String path = "http://api.bit.ly/v3/shorten?&login=netafull&apiKey=R_8826b2745cfe264aa2047bd73277479b&longUrl=http://netafull.dev.vc/report/?id="+newsID+"&format=xml";
					list = analyze.getRss(path);
					
					if (content != null && list.size()!=0) {
						//String temp = content.getDescription().replace("&lt;img", "&lt;img onerror=this.src=&apos;file:///android_asset/onerror.png&apos").replace("http://netafull.net/images2009/2011-07-28_1153.png", "http://www.baidu.com/");
						String temp = content.getDescription().replace("&lt;img", "&lt;img onerror=this.src=&apos;file:///android_asset/onerror.png&apos");
						sDecode = StringEscapeUtils.unescapeHtml4(StringEscapeUtils
								.unescapeHtml4(temp));
						webView.loadDataWithBaseURL("", sDecode, "text/html",
								"utf-8", "");
						//contentShotUrl = content.getShort_url();
						message.what = STATUS_OK;
						
						
						if(list.size()!=0){
							contentShotUrl = list.get(0).getUrl();
							System.out.println("--------------->"+contentShotUrl);
						}
						
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("数据请求超时");
					message.what = STATUS_ERR;
				} finally{
					handler.sendMessage(message);
				}
				
				
				/*if (content != null) {
					sDecode = StringEscapeUtils.unescapeHtml4(StringEscapeUtils
							.unescapeHtml4(content.getDescription()));
					webView.loadDataWithBaseURL("", sDecode, "text/html",
							"utf-8", "");
					
					message.what = STATUS_OK;
					handler.sendMessage(message);
				}*/
			};
		};
		t.start();
	}
	private void showNetBusy(){
		new AlertDialog.Builder(this).setTitle("当前网络繁忙，请稍候再试！")
		.setPositiveButton(R.string.newnews_back, new AlertDialog.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if (t.isAlive()) {
					System.out.println("当前线程正在运行，强行中断");
					t.interrupt();
				}
				NewsContent.this.finish();
			}
		}).create().show();
	}
	public void openMenu(){
		System.out.println(menu_display);
		if(!menu_display){
			
			//category_progress = layout.findViewById(R.id.category_list_progress);
			
			menuWindow.setAnimationStyle(R.style.PopupAnimation);
			menuWindow.showAtLocation(layout.findViewById(R.id.popuwindow), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
			//menuWindow.setFocusable(true);
			
			menuWindow.update();
			
			menu_display = true;
			
			
		}else{
			//如果当前已经为显示状态，则隐藏起来
			
			menuWindow.dismiss();
			menuWindow.setFocusable(false);
			menu_display = false;
			
		}
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_popup01://评论
			b = true;
			menuWindow.dismiss();
			Intent intent = new Intent(this, NewsComments.class);
			Bundle bundle = new Bundle();
			bundle.putInt("id", newsID);
			bundle.putString("title", newsTitle);
			intent.putExtras(bundle);
			startActivityForResult(intent,100);
			
			menu_display = false;
			break;
		case R.id.btn_popup02://发信
			b = true;
			menuWindow.dismiss();
			final Intent emailit = new Intent(Intent.ACTION_SEND);
			//邮件标题
			emailit.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.email_default_title4));
			//正文
			if (contentShotUrl == null)
			{
				//t.start();
				new Thread(){
					@Override
					public void run() {
						// TODO Auto-generated method stub
						try {
							
							content = analyzeXML.getRss(newsUrl);
							
							String path = "http://api.bit.ly/v3/shorten?&login=netafull&apiKey=R_8826b2745cfe264aa2047bd73277479b&longUrl=http://netafull.dev.vc/report/?id="+newsID+"&format=xml";
							list = analyze.getRss(path);
							
							if (content != null && list.size()!=0) {
								
								contentShotUrl = list.get(0).getUrl();
								
								String  Xinghao = android.os.Build.MODEL;
								emailit.putExtra(Intent.EXTRA_TEXT, newsTitle+"\n"+contentShotUrl+"\n"+"\n"+
										getResources().getString(R.string.popwindow_email_content)+"\n"+"\n"+"\n"+Xinghao+
										getResources().getString(R.string.popwindow_email_content_xinghao));
								emailit.setType("text/plain"); //纯文本则用text/plain的mime
								startActivityForResult(emailit, 1);
								
								menu_display = false;
								
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
							
						} 
						super.run();
					}
				}.start();
			} else {
				String  Xinghao = android.os.Build.MODEL;
				emailit.putExtra(Intent.EXTRA_TEXT, newsTitle+"\n"+contentShotUrl+"\n"+"\n"+
						getResources().getString(R.string.popwindow_email_content)+"\n"+"\n"+"\n"+Xinghao+
						getResources().getString(R.string.popwindow_email_content_xinghao));
				emailit.setType("text/plain"); //纯文本则用text/plain的mime
				startActivityForResult(emailit, 1);
				
				menu_display = false;
			}
			
			break;
		case R.id.btn_popup03://Twitter
			b = true;
			Intent intentForTwitter = new Intent(this, TwitterPage.class);
			Bundle b = new Bundle();
			b.putInt("id", newsID);
			System.out.println("id===="+newsID);
			b.putString("title", newsTitle);
			b.putString("url", Content.short_url);
			System.out.println("id="+newsID+",title="+newsTitle+","+Content.short_url);
			intentForTwitter.putExtras(b);
			startActivityForResult(intentForTwitter,100);
			if(menuWindow.isShowing()){
				menuWindow.dismiss();
			}
			
			menu_display = false;
			break;
		case R.id.btn_popup04://取消
			openMenu();
			break;
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if(keyCode == KeyEvent.KEYCODE_BACK){
			if(menuWindow.isShowing()){
				menuWindow.dismiss();
				menu_display = false;
				return false;
			} else if(t.isAlive()){
				t.interrupt();
				System.out.println("线程正在运行，强行中断");
			}
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	@Override
	protected void onUserLeaveHint() {
		// TODO Auto-generated method stub
		super.onUserLeaveHint();
		if(!b){
			if(sp!=null){
				Editor editor = sp.edit();
				editor.clear();
				editor.commit();
			}
			System.out.println("开始销毁Activity");
			CloseUtil.closeActivity();
		}else{
			System.out.println("没有销毁Activity");
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		b = false;
	}
}
